$(function() {
	var startDate = moment().subtract('days', 6);// 7 days ago
	var endDate = moment();
	var cb = function(start, end, label) {
		console.log(start.toISOString(), end.toISOString(), label);
		startDate = start;
		endDate = end;
		$('#reportrange span').html(
				start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
	};

	var optionSet1 = {
		startDate : startDate,
		endDate : startDate,
		showDropdowns : true,
		//showWeekNumbers : true,
		timePicker : false,
		timePickerIncrement : 1,
		timePicker12Hour : true,
		ranges : {
			'今天' : [ moment(), moment() ],
			'昨天' : [ moment().subtract('days', 1),
					moment().subtract('days', 1) ],
			'最近7天' : [ moment().subtract('days', 6), moment() ],
			'最近30天' : [ moment().subtract('days', 29), moment() ],
			'当前月份' : [ moment().startOf('month'), moment().endOf('month') ],
			'上个月份' : [ moment().subtract('month', 1).startOf('month'),
					moment().subtract('month', 1).endOf('month') ]
		},
		opens : 'left',
		buttonClasses : [ 'btn btn-default' ],
		applyClass : 'btn-small btn-primary',
		cancelClass : 'btn-small',
		format : 'YYYY-MM-DD',
		separator : ' to ',
		locale : {
			applyLabel : '确定',
			cancelLabel : '取消',
			fromLabel : '从',
			toLabel : '到',
			customRangeLabel : '自定义区间',
			daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
			monthNames : [ '一月', '二月', '三月', '四月', '五月',
					'六月', '七月', '八月', '九月', '十月',
					'十一月', '十二月' ],
			firstDay : 1
		}
	};

	$('#reportrange span').html(
			moment().subtract('days', 6).format('YYYY/MM/DD') + ' - '
					+ moment().format('YYYY/MM/DD'));

	$('#reportrange').daterangepicker(optionSet1, cb);
	$('#reportrange').on('apply.daterangepicker', function(ev, picker) {
		ajaxLoadChart(picker.startDate, picker.endDate, $("#projectId").val());
	});
	$('#reportrange').on('cancel.daterangepicker', function(ev, picker) {
		console.log("cancel event fired");
	});
	$("#tree")
			.dynatree(
					{
						selectMode : 1,
						onClick : function(node) {
							if (!node.data.isFolder) {
								// alert("You activated " + node.data.title);
								$("#projectName")
										.val(
												node.getParent().getParent()
														.getParent().data.title
														+ node.getParent()
																.getParent().data.title
														+ node.getParent().data.title
														+ node.data.title);
								$("#projectId").val(node.data.key);
								ajaxLoadChart(startDate, endDate, node.data.key);
								$("#all").show();
								$("#tree").hide();
							}
						},
						initAjax : {
							url : window.basePath + "project/loadProject"
						},
					});

	// $("#projectName").click(function() {
	// $("#tree").toggle();
	// });
	// $("#tree").mouseleave(function() {
	// $("#tree").hide();
	// });

	$("#projectName").click(function(event) {
		$("#tree").toggle();
		$(document).one("click", function() {// 对document绑定一个影藏Div方法
			$("#tree").hide();
		});
		event.stopPropagation();// 点击Button阻止事件冒泡到document
	});
	$("#tree").click(function(event) {
		event.stopPropagation();// 在Div区域内的点击事件阻止冒泡到document
	});

	// The tooltip shown over the chart
	var tt = $('<div class="ex-tooltip">').appendTo('body'), topOffset = -32;

	var data = {
		"xScale" : "time",
		"yScale" : "linear",
		"main" : [ {
			className : ".stats",
			"data" : []
		} ]
	};

	var opts = {
		paddingLeft : 50,
		paddingTop : 20,
		paddingRight : 10,
		axisPaddingLeft : 25,
		tickHintX : 9, // How many ticks to show horizontally

		dataFormatX : function(x) {

			// This turns converts the timestamps coming from
			// ajax.php into a proper JavaScript Date object

			return Date.create(x);
		},

		tickFormatX : function(x) {

			// Provide formatting for the x-axis tick labels.
			// This uses sugar's format method of the date object.

			return x.format('{yyyy}/{MM}/{dd}');
		},

		"mouseover" : function(d, i) {
			var pos = $(this).offset();

			tt.text(d.x.format('{yyyy}/{MM}/{dd} {HH}:{mm}:{ss}') + ': ' + d.y)
					.css({

						top : topOffset + pos.top,
						left : pos.left

					}).show();
		},

		"mouseout" : function(x) {
			tt.hide();
		}
	};

	// Create a new xChart instance, passing the type
	// of chart a data set and the options object

	var heatChart = new xChart('line-dotted', data, '#heatChart', opts);
	var areaChart = new xChart('line-dotted', data, '#areaChart', opts);
	var periodChart = new xChart('line-dotted', data, '#periodChart', opts);

	// Function for loading data via AJAX and showing it on the chart
	function ajaxLoadChart(startDateP, endDateP, projectId) {

		// If no data is passed (the chart was cleared)

		if (!startDateP || !endDateP) {
			heatChart.setData({
				"xScale" : "time",
				"yScale" : "linear",
				"main" : [ {
					className : ".stats",
					data : []
				} ]
			});
			areaChart.setData({
				"xScale" : "time",
				"yScale" : "linear",
				"main" : [ {
					className : ".stats",
					data : []
				} ]
			});
			periodChart.setData({
				"xScale" : "time",
				"yScale" : "linear",
				"main" : [ {
					className : ".stats",
					data : []
				} ]
			});

			return;
		}

		// Otherwise, issue an AJAX request
		$.ajax({
			url : window.basePath + "data/heatTrends",
			data : {
				start : startDateP.format('YYYY-MM-DD'),
				end : endDateP.format('YYYY-MM-DD'),
				projectId : projectId
			},
			type : 'POST',
			success : function(data) {
				if (!data.isEmpty()) {
					$("#heatContent").show();
					$("#heatError").hide();
					var set = [];
					$.each(data, function() {
						set.push({
							x : this.label,
							y : parseInt(this.value, 10)
						});
					});

					heatChart.setData({
						"xScale" : "time",
						"yScale" : "linear",
						"main" : [ {
							className : ".stats",
							data : set
						} ]
					});
				} else {
					$("#heatContent").hide();
					$("#heatError").show();
				}
			}
		});
		$.ajax({
			url : window.basePath + "data/areaTrends",
			data : {
				start : startDateP.format('YYYY-MM-DD'),
				end : endDateP.format('YYYY-MM-DD'),
				projectId : projectId
			},
			type : 'POST',
			success : function(data) {

				if (!data.isEmpty()) {
					$("#areaContent").show();
					$("#areaError").hide();
					var set = [];
					$.each(data, function() {
						set.push({
							x : this.label,
							y : parseInt(this.value, 10)
						});
					});

					areaChart.setData({
						"xScale" : "time",
						"yScale" : "linear",
						"main" : [ {
							className : ".stats",
							data : set
						} ]
					});
				} else {
					$("#areaContent").hide();
					$("#areaError").show();
				}
			}
		});
		$.ajax({
			url : window.basePath + "data/periodTrends",
			data : {
				start : startDateP.format('YYYY-MM-DD'),
				end : endDateP.format('YYYY-MM-DD'),
				projectId : projectId
			},
			type : 'POST',
			success : function(data) {
				if (!data.isEmpty()) {
					$("#periodContent").show();
					$("#periodError").hide();
					var set = [];
					$.each(data, function() {
						set.push({
							x : this.label,
							y : parseInt(this.value, 10)
						});
					});

					periodChart.setData({
						"xScale" : "time",
						"yScale" : "linear",
						"main" : [ {
							className : ".stats",
							data : set
						} ]
					});
				} else {
					$("#periodContent").hide();
					$("#periodError").show();
				}

			}
		});
	}
});
